from sklearn.datasets import _samples_generator
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectKBest,f_regression
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
# 生成样本数据
X,y = _samples_generator.make_classification(n_informative=4,n_features=20,n_redundant=0,random_state=5)
X_train,X_test,y_train,y_test= train_test_split(X,y,random_state=2)
# print(X[:5],y[:5])
# 特征选择器
# 单变量统计
selector_k_best = SelectKBest(f_regression,k=10)
# 随机森林分类器
classifier = RandomForestClassifier(n_estimators=50,max_depth=4)
# 构建机器学习管道
pipeline_classifier = Pipeline([('selector',selector_k_best),('rf',classifier)])
# 通关管道修改参数
# pipeline_classifier.set_params(selector__k=6,rf__n_estimators=25)
# 训练分类器
pipeline_classifier.fit(X_train,y_train)
# 预测输出结果
prediction = pipeline_classifier.predict(X_test)
print("预测结果:",prediction)
print("真实结果:",y_test)
print("分类器精度:",round(pipeline_classifier.score(X_test,y_test),2))
# 打印出选取的特征
f_index = []
feature_status = pipeline_classifier.named_steps['selector'].get_support()
for count,item in enumerate(feature_status):
    if item:
        f_index.append(count)
print(f_index)